package com.ruoyi.yn.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.exception.yn.YnBusinessExceptions;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.yn.domain.YnWxUser;
import com.ruoyi.yn.vo.YnWxUserVo;
import com.ruoyi.yn.mapper.YnWxUserMapper;
import com.ruoyi.yn.service.IYnWxUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 微信小程序授权信息Service业务层处理
 *
 * @author Tellsea
 * @date 2023-04-24
 */
@Service
public class YnWxUserServiceImpl extends ServiceImpl<YnWxUserMapper, YnWxUser> implements IYnWxUserService {

    @Resource
    private WxMaService wxMaService;

    @Override
    public TableDataInfo<YnWxUserVo> queryList(YnWxUserVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<YnWxUserVo> queryAll(YnWxUserVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public YnWxUserVo queryById(String id) {
        return this.baseMapper.queryById(id);
    }

    @Override
    public YnWxUser userLogin(String code, String encryptedData, String ivStr) {
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            //查询微信小程序用户信息，不存在则获取用户信息
            String openid = session.getOpenid();
            YnWxUser ynWxUser = lambdaQuery().eq(YnWxUser::getOpenId, openid).one();
            if (ObjectUtil.isNotEmpty(ynWxUser)) {
                lambdaUpdate().eq(YnWxUser::getId,ynWxUser.getId())
                        .set(YnWxUser::getLastLoginTime, DateUtil.now()).update();
                return ynWxUser;
            }
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), encryptedData, ivStr);
            YnWxUser wxUser = BeanUtil.toBean(userInfo, YnWxUser.class);
            String idStr = IdWorker.getIdStr();
            wxUser.setId(idStr);
            wxUser.setOpenId(openid);
            save(wxUser);
            return wxUser;
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new YnBusinessExceptions(e.getMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }
}
